package com.ygqh.baby.controller.admin;

import com.ygqh.baby.annotation.ProductLog;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.controller.utils.DocumentHandler;
import com.ygqh.baby.model.SkuBasicData;
import com.ygqh.baby.model.YgProduct4ListModel;
import com.ygqh.baby.model.YgSkuInfo;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.impl.GenerateStaticPages;
import com.ygqh.baby.shiro.utils.SessionUtil;
import com.ygqh.baby.utils.HttpUtil;
import com.ygqh.baby.utils.InternetWormUtils;
import com.ygqh.baby.utils.JsonUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin/product")
public class ProductController extends BaseController<Object, java.lang.Long> {


    @Autowired
    private YgProductService ygProductService;
    @Autowired
    private YgCategoryService ygCategoryService;
    @Autowired
    private YgSkuService ygSkuService;
    @Autowired
    private FileService fileService;
    @Autowired
    private AdminSkuService adminSkuService;
    @Autowired
    private YgSkuMaterialService ygSkuMaterialService;

    @Value("${image.upload.temp.url}")
    private String tempUrl;
    @Value("${oss.aliyun.endpoint}")
    private String endpoint;
    @Value("${oss.aliyun.templatebucketName}")
    private String templatebucketName;
    @Value("${product.template.filename}")
    private String templateFileName;
    @Autowired
    private GenerateStaticPages generateStaticPages;

    @RequestMapping("searchProduct")
    @ResponseBody
    public Map<String, Object> searchProduct(String q, QueryInfo queryInfo, String productStatus, String groupName,
                                             Boolean isSpecial, String productCode, Boolean isGroup, String supplierName,
                                             Boolean preSaleDate, SalesPlatform salesPlatform) {
        if (isSpecial != null && !isSpecial) {
            isSpecial = null;
        }
        ResultSet<Map<String, Object>> resultSet = ygProductService.search(queryInfo, q, groupName, productStatus,
                supplierName, isSpecial, productCode, isGroup, preSaleDate, salesPlatform);
        return resultSet.toDatatables(null);
    }

    @ProductLog(description = "新增/更新商品", params = {"product", "productCode"})
    @RequestMapping("saveProduct")
    @ResponseBody
    public Message saveProduct(String product, String productCode) throws Exception {
        YgProduct p = JsonUtils.toObject(product, YgProduct.class);
        p.setCreateBy(getSession().getTrueName());
        if (p.getId() != null) {
            p.setUpdateBy(getSession().getTrueName());
            p.setUpdateTime(new Date());
            // 判断有新客价时 是否存在自选礼包活动
            if (!p.getNewCustomPrice().equals(BigDecimal.ZERO)) {
                if (ygProductService.IsExistPackByProductId(p.getId())) {
                    return Message.error("商品已参与N元任选活动,不能设置新客价");
                }
            }
            // 判断sku是否存在 admin_sku 表中
            List<String> skuList = new ArrayList<String>();

            for (YgSku sku : p.getYgSkus()) {
                if (sku.getStatus().equals(DataStatus.Valid))
                    skuList.add(sku.getSkuCode());
            }

            // 如果原产品编码与现在的产品编码不一致，则删除产品的sku
            if (!productCode.equals(p.getProductCode())) {
                YgSku ygSku = new YgSku();
                ygSku.setProductId(p.getId());
                ygSku.setStatus(DataStatus.Delete);
                ygSku.setUpdateBy(getSession().getTrueName());
                ygSku.setUpdateTime(new Date());
                ygSkuService.updateByProductId(ygSku);
            }
        } else {
            p.setCreateTime(new Date());
        }
        p.setForeverRate(new BigDecimal("0.02"));
        if (ygProductService.saveOrUpdate(p) == 1) {
            return Message.success(p.getId());
        }
        return ERROR_MESSAGE;
    }

    @ProductLog(description = "删除商品", params = {"id"})
    @RequestMapping("updateProductStatus")
    @ResponseBody
    public Message updateProductStatus(Long id) {
        YgProduct ygProduct = new YgProduct();
        ygProduct.setId(id);
        ygProduct.setUpdateBy(getSession().getTrueName());
        ygProduct.setUpdateTime(new Date());
        ygProduct.setStatus(DataStatus.Delete);

        YgSku ygSku = new YgSku();
        ygSku.setProductId(id);
        ygSku.setUpdateBy(getSession().getTrueName());
        ygSku.setUpdateTime(new Date());
        ygSkuService.update(ygSku);

        return ygProductService.updateProductStatus(ygProduct) == 1 ? SUCCESS_MESSAGE : ERROR_MESSAGE;
    }

    @ProductLog(description = "上/下架商品", params = {"id", "saleStatus", "saleTime", "productCode"})
    @RequestMapping("updateSalesStatus")
    @ResponseBody
    public Message updateSalesStatus(Long id, ProductStatus saleStatus, Date saleTime, String productCode) {
        YgProduct ygProduct = new YgProduct();
        ygProduct.setId(id);
        ygProduct.setUpdateBy(getSession().getTrueName());
        ygProduct.setUpdateTime(new Date());
        ygProduct.setSaleStatus(saleStatus);
        if (!saleStatus.equals(ProductStatus.InStock) && saleTime != null)
            ygProduct.setSaleTime(saleTime);
        if (!saleStatus.equals(ProductStatus.InStock) && saleTime == null)
            ygProduct.setSaleTime(new Date());
        //先判断上架的商品是否维护成本
        if (saleStatus.equals(ProductStatus.OnSale)) {
            List<YgSkuMaterial> costlist = ygSkuMaterialService.findSkuCostByProductId(productCode);
            if (costlist == null || costlist.size() == 0) {
                return Message.error("请先维护SKU的成本");
            } else {
                boolean isExist = false;
                for (YgSkuMaterial m : costlist) {
                    if (m.getCostPrice().compareTo(new BigDecimal(0)) == 0) {
                        isExist = true;
                        break;
                    }
                }
                if (isExist) {
                    return Message.error("请先维护SKU的成本");
                }

            }
        }

        Message msg = ygProductService.updateSaleStatus(ygProduct) == 1 ? SUCCESS_MESSAGE : ERROR_MESSAGE;
        if (msg.getType().equals(Message.Type.success)) {
            ygProductService.pushToWDT(id);
        }
        return msg;
    }

    @ProductLog(description = "设置商品预售", params = {"id", "preSaleDate"})
    @RequestMapping("updatePreSaleDate")
    @ResponseBody
    public Message updatePreSaleDate(Long id, Date preSaleDate) {
        return ygProductService.updatePreSaleDate(id, preSaleDate, getSession().getTrueName()) == 1 ? SUCCESS_MESSAGE : ERROR_MESSAGE;
    }

    @RequestMapping("getProductById")
    @ResponseBody
    public YgProduct getProductById(Long id) {
        return ygProductService.findDetailById(id);
    }

    @RequestMapping("findProductByIds")
    @ResponseBody
    public List<YgProduct> findProductByIds(Long[] ids) {
        return ygProductService.findByIds(ids);
    }

    @RequestMapping("getProductByGroupId")
    @ResponseBody
    public YgProduct getProductByGroupId(Long groupId) {

        return ygProductService.findDetailByGroupId(groupId).get(0);

    }

    @RequestMapping("getParentCategory")
    @ResponseBody
    public List<YgCategory> getParentCategory() {
        return ygCategoryService.findTopLevel();
    }

    @RequestMapping("getCategoryByParentId")
    @ResponseBody
    public List<YgCategory> getCategoryByParentId(@RequestParam(defaultValue = "0") Long parentId) {
        return ygCategoryService.findByParentId(parentId);
    }

    @RequestMapping("searchProductList")
    @ResponseBody
    public Map<String, Object> searchProductList(String q, QueryInfo queryInfo, Long packId) {

        ResultSet<YgProduct4ListModel> result = ygProductService.findOrdinaryProductNotPack(q, queryInfo, packId);
        return result.toDatatables(null);
    }

    @RequestMapping("searchProductListForPromotion")
    @ResponseBody
    public Map<String, Object> searchProductListForPromotion(String q, Long promotionId) {

        List<YgProduct> list = ygProductService.findProductForPromotion(null, q, null, null, null, promotionId, null);
        ResultSet<YgProduct> result = new ResultSet<YgProduct>(1, list);

        return result.toDatatables(null);
    }

    @RequestMapping("searchOrdinaryProductList")
    @ResponseBody
    public Map<String, Object> searchOrdinaryProductList(String q, Long groupId) {

        List<YgProduct> list = ygProductService.findOrdinaryOnSaleProducts(q, groupId, null);
        ResultSet<YgProduct> result = new ResultSet<YgProduct>(1, list);
        return result.toDatatables(null);
    }

    @RequestMapping("getProductListToPromotion")
    @ResponseBody
    public Map<String, Object> getPromotion(Long promotionId, String productName, Long groupId) {
        QueryInfo queryInfo = new QueryInfo();
        queryInfo.setEnd(200);
        List<YgProduct> list = ygProductService.findProductForPromotion(queryInfo, productName, groupId, ProductStatus.OnSale.name(), null, promotionId, null);
        ResultSet<YgProduct> result = new ResultSet<YgProduct>(1, list);
        return result.toDatatables(null);
    }

    @RequestMapping("checkProductCode")
    @ResponseBody
    public Boolean checkProductCode(String productCode, Long id) {

        return ygProductService.productCodeExist(productCode, id);
    }

    @RequestMapping("checkSkuCode")
    @ResponseBody
    public Boolean checkSkuCode(String skuCode, Long id) {
        return ygSkuService.skuCodeExist(skuCode, id);
    }

    @RequestMapping("getParentsByCategoryId")
    @ResponseBody
    public List<YgCategory> getParentsByCategoryId(Long categoryId) {
        return ygCategoryService.findParentsByCategoryId(categoryId);
    }

    @RequestMapping("getSkuByProductId")
    @ResponseBody
    public List<YgSku> getSkuByProductId(Long productId) {
        return ygSkuService.find(productId);
    }

    @RequestMapping("updateWholesalePrice")
    @ResponseBody
    public Message updateWholesalePrice(String product) {
        YgProduct p = JsonUtils.toObject(product, YgProduct.class);
        p.setUpdateTime(new Date());
        p.setUpdateBy(getSession().getTrueName());
        ygProductService.updateWholesalePrice(p);
        return SUCCESS_MESSAGE;

    }

    @RequestMapping("updateCostPrice")
    @ResponseBody
    public Message updateCostPrice(String product) {
        YgProduct p = JsonUtils.toObject(product, YgProduct.class);
        ygProductService.updateCostPrice(p);
        return SUCCESS_MESSAGE;

    }

    @ProductLog(description = "商品一键改价", params = {"product"})
    @RequestMapping("updateSalesPrice")
    @ResponseBody
    public Message updateSalesPrice(String product) {
        YgProduct p = JsonUtils.toObject(product, YgProduct.class);
        p.setUpdateTime(new Date());
        p.setUpdateBy(getSession().getTrueName());
        ygProductService.updateSalesPrice(p);
        return Message.success(p.getId());

    }

    @ProductLog(description = "设置特例品", params = {"id", "isSpecial"})
    @RequestMapping("siteSpecial")
    @ResponseBody
    public Message siteSpecial(Long id, Boolean isSpecial) {
        return ygProductService.siteSpecial(id, isSpecial);
    }

    @RequestMapping("exportSkuCost")
    public void exportSkuCost(String productName, String productCode, Long groupId, String skuCode, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
//		if (groupId == -1)
//		 groupId = null;
        QueryInfo queryInfo = new QueryInfo();
        queryInfo.setEnd(100000);
        List<AdminSku> list = adminSkuService.selectSuperByProduct(queryInfo, productName, productCode, skuCode, groupId);

        // InputStream
        // inputStream=OrderController.class.getClassLoader().getResourceAsStream("/template/orderlist.xls");//"template/orderlist.xls";
        byte[] bytes = fileService.downloadFromOss("template/skuCost.xls"); // ByteToInputStream.input2byte(inputStream);
        List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("resultSet", list);
        dataMaps.add(dataMap);
        DocumentHandler.DownloadExcel(bytes, "商品成本.xls", dataMap, request, response);
    }

    @RequestMapping("exportProduct")
    public void exportProduct(String productName, String productStatus, String groupName, Boolean special, String productCode, Boolean isGroup, String supplierName,
                              Boolean preDate, SalesPlatform salesPlatform, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //选获取总行数
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        int count = ygProductService.countHoutaiProductList(productName, groupName, productStatus, supplierName, special, productCode, isGroup, preDate, salesPlatform);
        if (count > 0) {
            QueryInfo q = new QueryInfo();
            int pages = count / 100;
            if (count % 100 > 0) pages++;
            for (int i = 1; i <= pages; i++) {
                q.setStart((i - 1) * 100);
                q.setLimit(i * 100);
                List<Map<String, Object>> sub = ygProductService.selectProductListToExport(q, productName, groupName, productStatus, supplierName, special, productCode, isGroup, preDate, salesPlatform);
                list.addAll(sub);
            }
        }

        byte[] bytes = fileService.downloadFromOss("template/productlist.xls");
        List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("resultSet", list);
        dataMaps.add(dataMap);
        DocumentHandler.DownloadExcel(bytes, "产品信息.xls", dataMap, request, response);
    }

    @SuppressWarnings("deprecation")
    @RequestMapping("getProductImagesByTmall")
    @ResponseBody
    public YgProduct getProductImagesByTmall(String tid, HttpServletRequest request) throws Exception {
        String path = "https://detail.m.tmall.com/item.htm?id=" + tid;
        YgProduct p = InternetWormUtils.getTmallImgPath(path);
        String localpath = request.getRealPath("/");
        String targetPath = localpath + "/ShareProductImage/second_" + tid + ".jpg";
        String temptPath = HttpUtil.saveImageToDisk("http:" + p.getProductImages().get(0).getImagePath(), targetPath);
        File file = new File(temptPath);
        FileType[] fileType = new FileType[]{FileType.ProductListImage, FileType.ProductDetailImage, FileType.ProductShoppingCartImage};

        String iamgepath = fileService.uploadImage(file, fileType, ".jpg", false, request);

        p.getProductImages().get(0).setImagePath(iamgepath);

        return p;
    }

    @RequestMapping("getSkuInfo")
    @ResponseBody
    public YgSkuInfo getSkuInfo(String skuCode, PromotionType pType, HttpServletRequest request) throws Exception {
        YgSkuInfo skuInfo = ygSkuService.getSkuInfo(skuCode, pType);
        return skuInfo;
    }

    @RequestMapping("reviewProduct")
    @ResponseBody
    public Message reviewProduct(Long id, HttpServletRequest request) {
        // 获取上架产品
        Message msg = null;
        if (id == null) {
            List<YgProduct> list = ygProductService.findProductList(null, null, null, null, null);
            if (CollectionUtils.isNotEmpty(list)) {
                List<Long> collect = list.stream().map(p -> p.getId()).collect(Collectors.toList());
                msg = generateStaticPages.reviewPage(collect.toArray(new Long[collect.size()]));
            }
        } else {
            msg = generateStaticPages.reviewPage(id);
        }
        return msg;
    }

    @RequestMapping("publishProduct")
    @ResponseBody
    public Message publishProduct(Long productId, String pageLink, HttpServletRequest request) throws IOException {
        // 判断是否已经预览了
        String fileName = productId + ".html";

        String url = endpoint.replace("oss", templatebucketName + ".oss") + "/review/" + fileName;
        String result = HttpUtil.get(url);
        if (result == null || result.contains("NoSuchKey")) {// 先预览
            return generateStaticPages.reviewPage(productId);

        } else {
            fileService.uploadTemplateHtml2Target("review/" + fileName, fileName);
            // 上传小程序页面
            // String smallFile=fileName.replace(".html", "_small.html");
            // fileService.uploadTemplateHtml2Target("review/"+smallFile,smallFile);
            return Message.success("发布", url);

        }
    }

    @RequestMapping("pushProductInfoToKids")
    @ResponseBody
    public Message pushProductInfoToKids(@RequestParam Long productId, @RequestParam OffShop... offShops) {
        return ygProductService.pushProductInfoToKids(productId, SessionUtil.getCurrentUser().getTrueName(), offShops);
    }

    @RequestMapping("pushProductInfoToKidsBatch")
    @ResponseBody
    public Message pushProductInfoToKidsBatch(@RequestParam Long[] productIds, @RequestParam OffShop... offShops) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Long productId : productIds) {
            Message message;
            try {
                message = ygProductService.pushProductInfoToKids(productId, SessionUtil.getCurrentUser().getTrueName(), offShops);
            } catch (Exception e) {
                message = Message.error(e.getMessage(), e);
            }
            if (!Message.Type.success.equals(message.getType())) {
                stringBuilder.append(productId).append(",");
            }
        }
        if (stringBuilder.length() == 0) {
            return Message.success(null);
        }
        return Message.error("以下商品推送失败" + stringBuilder.toString(), stringBuilder.toString());
    }

    @RequestMapping("batchUpdateProdctName")
    @ResponseBody
    public Message batchUpdateProductName(String searchKey, @RequestParam String distProductName, String[] productIds) {
        //按名称关键字替换
        if (!StringUtils.isEmpty(searchKey)) {
            return ygProductService.batchUpdateProdctName(searchKey, distProductName, SessionUtil.getCurrentUser().getTrueName(), new Date());
        }
        //按产品ID 增加前缀
        return ygProductService.batchUpdateProdctByProductIds(productIds, distProductName, SessionUtil.getCurrentUser().getTrueName(), new Date());

    }

    @RequestMapping("getBasicDataList")
    @ResponseBody
    public Map getBasicDataList(String productName) {
        List<SkuBasicData> basicDataList = ygSkuService.getBasicDataList(PromotionType.Ordinary, productName);
        return new ResultSet(basicDataList.size(), basicDataList).toDatatables(null);
    }

}
